/* eslint-disable no-template-curly-in-string */
import {
  IFilterNodeField,
  SearchBarFilterController,
} from '@ibiz-template/runtime';
import { ScriptValueRegex } from './filter-search-bar.controller';

/**
 * 过滤节点项数据
 *
 * @export
 * @interface IFilterNodeItem
 * @extends {IFilterNodeField}
 */
export interface IFilterNodeItem extends IFilterNodeField {
  /**
   * 复合编辑项值
   *
   * @type {IData}
   * @memberof IFilterNodeItem
   */
  editorItems?: IData;
}

/**
 * 过滤项控制器
 * - 重写了标准的搜索栏过滤项控制器特殊处理复合编辑器项值变更
 * @export
 * @class FilterItemController
 * @extends {SearchBarFilterController}
 */
export class FilterItemController extends SearchBarFilterController {
  /**
   * 复合编辑器项
   *
   * @readonly
   * @type {(string[] | undefined)}
   * @memberof FilterItemController
   */
  get editorItems(): string[] | undefined {
    return this.editor?.model.editorItems?.map((item: IData) => item.id);
  }

  /**
   * 计算要递给编辑器的参数
   *
   * @param {IFilterNodeItem} node
   * @return {*}  {{ value: unknown; data: IData }}
   * @memberof FilterItemController
   */
  calcEditorProps(node: IFilterNodeItem): { value: unknown; data: IData } {
    const tempData: IData = {};
    let editorValue = node.value as string;
    if (node.disabled && ScriptValueRegex.test(editorValue)) {
      editorValue = editorValue.replace('${context.srfpersonid}', '当前用户');
      editorValue = editorValue.replace('${context.srforgid}', '当前组织');
    }

    if (this.valueItem) {
      tempData[this.valueItem] = node.valueItem;
    }

    if (this.editorItems && node.editorItems) {
      Object.assign(tempData, node.editorItems);
    }

    return { value: editorValue, data: tempData };
  }

  /**
   * 编辑器值变更处理
   *
   * @param {IFilterNodeItem} node
   * @param {unknown} value
   * @param {string} [name]
   * @memberof FilterItemController
   */
  onEditorChange(node: IFilterNodeItem, value: unknown, name?: string): void {
    if (this.valueItem && name === this.valueItem) {
      node.valueItem = value;
    } else if (this.editorItems && name && this.editorItems.includes(name)) {
      if (!node.editorItems) {
        node.editorItems = {};
      }
      Object.assign(node.editorItems, { [name]: value });
    } else {
      node.value = value;
    }
  }
}
